package com.ciwong.epaper.modules.epaper.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.Node;
import com.ciwong.epaper.modules.epaper.bean.PackageInfo;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.utils.BaseJumpManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 多层次目录结构
 * Created by lzr on 2016/11/15.
 */
public class LayersView extends LinearLayout {


    private final String TAG = "LayersView";

    private LayoutInflater inflater;
    private List<Node> nodes = new ArrayList<>();
    //    private List<LayersBean> layersBeans;
    private Context mContext;
    private ItemClick cilck;
    //一个业务属于可以抽出来
    private boolean isPack;
    //业务集合
    private List<CatalogueInfo> catalogueInfos;
    private List<View> layoutList = new ArrayList<>();

    //业务先关的变量
    private boolean sortState = true;

    private List<DownLoadInfo> mDownLoadInfoList;

    //来源
    private int form;
    //考试用书
    private int kaoShi;

    private List<String> bookchapters;

    public void setCatalogueInfos(List<CatalogueInfo> catalogueInfos) {
        this.catalogueInfos = catalogueInfos;

        sortNode(catalogueInfos);
        bindLinearLayout();
    }


    public void setBookchapters(List<String> bookchapters) {
        this.bookchapters = bookchapters;
    }

    public void setForm(int form) {
        this.form = form;
    }

    public void setKaoShi(int kaoShi) {
        this.kaoShi = kaoShi;
    }

    public void setSortState(boolean sortState) {
        this.sortState = sortState;
    }


    private boolean isKaoshiPass(String bookId) {
        if (bookchapters == null) {
            return false;
        }
        for (int i = 0; i < bookchapters.size(); i++) {
            if (bookchapters.get(i).equals(bookId)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 排序
     */
    public boolean sort() {
        Collections.reverse(layoutList);
        this.removeAllViews();
        for (int i = 0; i < layoutList.size(); i++) {
            this.addView(layoutList.get(i));
        }
        if (sortState) {
            sortState = false;
        } else {
            sortState = true;
        }
        return sortState;
    }


    /**
     * 此构造函数用于布局中
     *
     * @param context
     * @param attrs
     */
    public LayersView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        inflater = LayoutInflater.from(context);
    }

    /**
     * 绑定布局
     */
    public void bindLinearLayout() {


        layoutList.clear();
        int count = nodes.size();
        this.removeAllViews();

        Log.d(TAG, "#########bindLinearLayout count##########" + count);

        for (int i = 0; i < count; i++) {

            final int finalI = i;
            final Node node = nodes.get(i);
            //父节点
            if (node.getpId() == 0) {
                View convertView;
                if ((node.getChildren() != null && node.getChildren().size() > 0) || isPack) {
                    convertView = getContextView(node);
                    //控制第一个一级目录下的条目展示“免费"
                    // TODO: 2018/7/2 服务页 暂时去掉免费试用
                  /*  if (form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE&&node.getIsFree()==1&&node==nodes.get(0)){
                        View tvFree = convertView.findViewById(R.id.tv_free_first);
                        tvFree.setVisibility(VISIBLE);
                    }*/
                    convertView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击的时候要显示
                            itemClick(node.getId(), v, node);
                        }
                    });
                } else {
                    //有可能第一项目就是最后一项
                    convertView = getLastView(node, true);
                    //控制第一个一级目录下的条目展示“免费"
                    // TODO: 2018/7/2 服务页 暂时去掉免费试用
                  /*  if (form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE&&node.getIsFree()==1&&node==nodes.get(0)){
                        View tvFree = convertView.findViewById(R.id.tv_free_three);
                        convertView.findViewById(R.id.item_iocn).setVisibility(VISIBLE);
                        tvFree.setVisibility(VISIBLE);
                    }*/
                    convertView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (cilck != null) {
                                //添加控制免费学习逻辑
                                if (!cilck.freeForLearnContralItemClick(finalI, node, nodes.get(0))) {
                                    return;
                                }
                                cilck.lastItemClick(node, v);
                            }
                        }
                    });
                }

                addView(convertView);
                //这个控件是有子控件的
                if (node.getChildren() != null && node.getChildren().size() > 0) {
                    //添加一个linearlayout用于添加子项
                    LinearLayout fristLin = (LinearLayout) convertView.findViewById(R.id.first_lin);
                    if (fristLin != null) {
                        fristLin.addView(getLinearLayout(node.getId()));

                        itemClick(node.getId(), convertView, node);
                    }
                }
                layoutList.add(convertView);
            } else {
                //既然是子控件那必然已经有一个以他父控件的LinearLayout
                LinearLayout chLayout = (LinearLayout) findViewById(node.getpId());
                if (chLayout != null) {
                    //这个控件是有子控件的
                    if (node.getChildren() != null && node.getChildren().size() > 0) {
                        //很明显是控件控件
                        View convertView = getChinldContextView(node);
                        //控制第一个一级目录下的条目展示“免费”
                        // TODO: 2018/7/2 服务页 暂时去掉免费试用
                       /* if (form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE&&node.getIsFree()==1&&node.getParent()!=null&&node.getParent()==nodes.get(0)){
                            View tvFree = convertView.findViewById(R.id.tv_free_two);
                            tvFree.setVisibility(VISIBLE);
                            //二级目录免费显示
//                            convertView.findViewById(R.id.sco_item_iocn).;
                        }*/
                        chLayout.addView(convertView);
                        //添加一个linearlayout用于添加子项
                        convertView.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //点击的时候要显示
                                itemClick(node.getId(), v, node);
                            }
                        });
                        chLayout.addView(getLinearLayout(node.getId()));
                        itemClick(node.getId(), convertView, node);
                    } else {
                        //显然是最后一个view了
                        View convertView = getLastView(node, false);
                        chLayout.addView(convertView);
                        // TODO: 2018/7/2 服务页 暂时去掉免费试用
                       /* if (form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE&&node.getIsFree()==1){
                           if ((node.getParent()!=null&&node.getParent()==nodes.get(0))//二级目录是最后一级
                                   ||(node.getParent().getParent()!=null&&node.getParent().getParent()==nodes.get(0))){//三级目录是最后一级
                                View tvFree = convertView.findViewById(R.id.tv_free_three);
                                tvFree.setVisibility(VISIBLE);
                                //当没有子目录时，展示右侧箭头
                                convertView.findViewById(R.id.item_iocn).setVisibility(VISIBLE);
                            }
                        }*/
                        convertView.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (cilck != null) {
                                    //添加控制免费学习逻辑
                                    //当购买后或者第一个一级条目可以向下直行
                                    if (!cilck.freeForLearnContralItemClick(finalI, node, nodes.get(0))) {
                                        return;
                                    }
                                    cilck.lastItemClick(node, v);
                                }
                            }
                        });
                    }
                }
            }
        }
    }

    private void itemClick(int id, View view, Node node) {
        LinearLayout chLayout = (LinearLayout) findViewById(id);
        //一级目录的图标
        ImageView imageView = (ImageView) view.findViewById(R.id.item_iocn);
        //二级目录的图标
        ImageView scImageView = (ImageView) view.findViewById(R.id.sco_item_iocn);
        View butView = view.findViewById(R.id.but_lin);
        if (chLayout != null) {
            if (chLayout.getVisibility() == GONE) {
                if (imageView != null) {
                    imageView.setImageResource(R.mipmap.icon_unit_unfold);
                }


                if (scImageView != null) {
                    scImageView.setImageResource(R.mipmap.icon_arrow_down);
                }
                if (butView != null) {
                    butView.setVisibility(View.GONE);
                }
                chLayout.setVisibility(VISIBLE);
            } else {
                chLayout.setVisibility(GONE);
                if (imageView != null) {
                    imageView.setImageResource(R.mipmap.icon_unit_fold);
                }
                if (scImageView != null) {
                    scImageView.setImageResource(R.mipmap.icon_arrow_up);
                }
                if (butView != null) {
                    butView.setVisibility(View.VISIBLE);
                }
            }
        }

        if (node.isLastItem()) {

            if (BaseApplication.PLATFORM_ENV != BaseApplication.PLATFORM_PAD) {

                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + mContext.getString(R.string.service_phone));
                intent.setData(data);
                intent.putExtra(BaseJumpManager.INTENT_FLAG_SOURCE, true);
                mContext.startActivity(intent);

            }
        }
    }

    public void setNodes(List<Node> nodes, boolean isPack) {
        this.nodes = nodes;
        this.isPack = isPack;
        if (isPack) {
            Node tNode = new Node(1, new PackageInfo(1, 1, "有疑问", "如有疑问，请拨打客服电话。"), true);
            this.nodes.add(tNode);
        }
        bindLinearLayout();
    }


    public void setOnItemClickListener(ItemClick cilck) {
        this.cilck = cilck;
    }

    private LinearLayout getLinearLayout(int id) {
        LinearLayout linearLayout = new LinearLayout(mContext);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(VERTICAL);
        linearLayout.setId(id);
        //默认情况下都是不显示的
        linearLayout.setVisibility(View.GONE);
        return linearLayout;
    }

    public interface ItemClick {
        void lastItemClick(Node node, View view);

        boolean freeForLearnContralItemClick(int item, Node node, Node node0);
    }

    /**
     * 第一级别
     *
     * @param node
     * @return
     */
    private View getContextView(Node node) {
        View convertView = inflater.inflate(R.layout.tree_first_item, null);
        TextView title = (TextView) convertView.findViewById(R.id.tree_title);
        if (node.getCatalogueInfo() != null) {
            title.setText(node.getCatalogueInfo().getName());
        } else if (node.getPackageInfo() != null) {
            return getDisView(node);
        }
        return convertView;
    }


    /**
     * 内容介绍页面
     *
     * @param node
     * @return
     */
    private View getDisView(Node node) {
        View convertView = inflater.inflate(R.layout.dis_content, null);
        TextView title = (TextView) convertView.findViewById(R.id.tree_title);
        TextView desTitle = (TextView) convertView.findViewById(R.id.tree_des);
        title.setText(node.getPackageInfo().getTitle());
        desTitle.setText(node.getPackageInfo().getContent());
        if (node.isLastItem()) {
            convertView.findViewById(R.id.last_item_iocn).setVisibility(View.VISIBLE);
        }
        return convertView;
    }

    /**
     * view
     * 之所以每个view分开就是不想耦合
     * 二级目录
     *
     * @param node
     * @return
     */
    private View getChinldContextView(Node node) {
        View convertView = inflater.inflate(R.layout.tree_sco_item, null);
        TextView title = (TextView) convertView.findViewById(R.id.tree_title);
        if (node.getCatalogueInfo() != null) {
            title.setText(node.getCatalogueInfo().getName());
        }
        return convertView;
    }

    /**
     * 最后一级别
     *
     * @param node
     * @param isFirst
     * @return
     */
    private View getLastView(Node node, boolean isFirst) {

//        Log.d(TAG, "#########getLastView##########");

        View convertView = inflater.inflate(R.layout.tree_last_item, null);
        TextView title = (TextView) convertView.findViewById(R.id.tree_title);
        TextView tvFree = (TextView) convertView.findViewById(R.id.tv_free_three);
        if (isFirst) {
            convertView.findViewById(R.id.temp_iocn).setVisibility(View.VISIBLE);
        } else if (node.getParent() != null && node.getParent().getParent() != null) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) title.getLayoutParams();
            layoutParams.setMargins(mContext.getResources().getDimensionPixelSize(R.dimen.linearn_margin), 0, 0, 0);
            title.setLayoutParams(layoutParams);
        }
        if (node.getCatalogueInfo() != null) {
            title.setText(node.getCatalogueInfo().getName());
        }

        DownLoadInfo info = getDownLoadInfo(node.getCatalogueInfo());
        ImageView imageView_download = (ImageView) convertView.findViewById(R.id.item_iocn);

        //考试用书
        if (kaoShi == 1 && !isKaoshiPass(node.getCatalogueInfo().getId())) {
            imageView_download.setImageResource(R.mipmap.icon_lock);
            node.setSuo(true);
            if (form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE
                    || form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs
//                    form == IntentValue.JumpToBookCatalogType.FROM_ADD_BOOK ||
//                    form == IntentValue.JumpToBookCatalogType.FROM_SEARCH_BOOK
                    ) {
                title.setTextColor(getResources().getColor(R.color.gray));
                imageView_download.setVisibility(View.INVISIBLE);
            }
        } else {
            if (form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE
                    || form == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs
//                    form == IntentValue.JumpToBookCatalogType.FROM_ADD_BOOK ||
//                    form == IntentValue.JumpToBookCatalogType.FROM_SEARCH_BOOK
                    ) {
                title.setTextColor(getResources().getColor(R.color.gray));
                imageView_download.setVisibility(View.INVISIBLE);
            } else {

                //新包结构直接是箭头
                if (node.getCatalogueInfo().getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
                    return convertView;
                }


                if (info != null) {
                    switch (info.getStatus()) {
                        case DownloadStatus.STATUS_COMPLETED:
                        case DownloadStatus.STATUS_PAUSE:
                        case DownloadStatus.STATUS_FAILED:
                        case DownloadStatus.STATUS_FAILED_SDISFULL:
                        case DownloadStatus.STATUS_FAILED_UNZIP:
                        case DownloadStatus.STATUS_DOWNLOADING:

                            if (info != null) {
                                Hoder hoder = new Hoder();
                                hoder.imageView_download = imageView_download;
                                dealCircleProgress(info, hoder);
                            }
                            break;
                        default:
                            break;
                    }

                }


            }
        }
        return convertView;
    }

    /**
     * 获取数据集合
     *
     * @param catalogueInfos
     */
    private void sortNode(List<CatalogueInfo> catalogueInfos) {
        nodes.clear();
        for (int i = 0; i < catalogueInfos.size(); i++) {
            Node node = new Node(Integer.valueOf(catalogueInfos.get(i).getId()), 0, catalogueInfos.get(i), null);
            node.setIsFree(catalogueInfos.get(i).getIsFree());
            nodes.add(node);
            if (catalogueInfos.get(i).getChildren() != null && catalogueInfos.get(i).getChildren().size() > 0) {
                List<Node> cList = new ArrayList<>();
                for (int j = 0; j < catalogueInfos.get(i).getChildren().size(); j++) {
                    Node cNode = new Node(Integer.valueOf(catalogueInfos.get(i).getChildren().get(j).getId()), node.getId(), catalogueInfos.get(i).getChildren().get(j), null);
                    cNode.setIsFree(catalogueInfos.get(i).getChildren().get(j).getIsFree());
                    cNode.setParent(node);
                    cList.add(cNode);
                    nodes.add(cNode);
                    if (catalogueInfos.get(i).getChildren().get(j).getChildren() != null && catalogueInfos.get(i).getChildren().get(j).getChildren().size() > 0) {
                        List<Node> lList = new ArrayList<>();
                        for (int k = 0; k < catalogueInfos.get(i).getChildren().get(j).getChildren().size(); k++) {
                            Node lNode = new Node(Integer.valueOf(catalogueInfos.get(i).getChildren().get(j).getChildren().get(k).getId()), cNode.getId(), catalogueInfos.get(i).getChildren().get(j).getChildren().get(k), null);
                            lNode.setIsFree(catalogueInfos.get(i).getChildren().get(j).getChildren().get(k).getIsFree());
                            lNode.setParent(cNode);
                            lList.add(lNode);
                            nodes.add(lNode);
                        }
                        cNode.setChildren(lList);
                    }
                }
                node.setChildren(cList);
            }

        }
    }

    private DownLoadInfo getDownLoadInfo(CatalogueInfo curInfo) {
        DownLoadInfo downLoadInfo = null;
        if (mDownLoadInfoList != null && mDownLoadInfoList.size() > 0) {
            for (int i = 0; i < mDownLoadInfoList.size(); i++) {
                Log.d("xixin", "--------getLastViewgetDownLoadInfo-----" + mDownLoadInfoList.get(i).getChapterId() + "-------" + curInfo.getId());
                if (mDownLoadInfoList.get(i).getChapterId().equals(curInfo.getId())) {
                    downLoadInfo = mDownLoadInfoList.get(i);
                    Log.d("xixin", "--------getLastViewgetDownLoadInfo-----" + downLoadInfo.getStatus());
                    break;
                }
            }
        }
        return downLoadInfo;
    }


    private void dealCircleProgress(final DownLoadInfo info, Hoder hoder) {
     /*   ProgressCircle progressCircle = hoder.progressCircle;
        TextView sizeText = hoder.sizeText;
        TextView speedText = hoder.speedText;
        hoder.imageView_download.setVisibility(View.GONE);
        progressCircle.setVisibility(View.VISIBLE);
        progressCircle.setIsError(false);
        switch (info.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
//                horPb.setProgress(0);
                progressCircle.updateDownloadProgress(0);
                progressCircle.setIsError(TextUtils.isEmpty(info.getUrl()));
                progressCircle.initToNormal();
                break;
            case DownloadStatus.STATUS_LOADING:
//                horPb.setProgress(0);
                progressCircle.initToLoading();
                //文件大小
                sizeText.setVisibility(View.VISIBLE);
                speedText.setVisibility(View.VISIBLE);
                sizeText.setText(info.getSize() + " MB");
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                DownLoadInfo currentInfo = DownLoad.getInstance()
                        .getCurrentBean(info);
                if (currentInfo != null) {
                    info.setProgress(currentInfo.getProgress());
                }

                //实时下载的网速
//                long downSpeed = getNetSpeed();
                speedText.setText(info.getProgress() + "/");

//                horPb.setProgress(info.getProgress());
                progressCircle
                        .updateDownloadProgress(info.getProgress() / 100f);
                break;
            case DownloadStatus.STATUS_COMPLETED:
                CWLog.e("TAT", "C1 ====== DownloadStatus.STATUS_COMPLETED !!!!!!!!!");
//                if (LIST_TYPE == CatalogActivity.LIST_ALL) {
                String packageDir = ESystem.getPackagesCatalogue(
                        info.getBookId(), info.getChapterId());
                Log.i("se7en", "LIST_ALL" + packageDir);
                if (new File(packageDir).exists()) {
//                        horPb.setProgress(0);
                    progressCircle.initToCompleted();
                } else {
//                    info.setProgress(0);
//                    DownLoad.getInstance().stopTask(info);
                    //这个状态表示没有下载成功
                    progressCircle.setVisibility(View.GONE);
                    hoder.imageView_download.setVisibility(VISIBLE);

                }
                speedText.setVisibility(View.GONE);
                sizeText.setVisibility(View.GONE);
                break;
            case DownloadStatus.STATUS_PAUSE:
//                horPb.setProgress(info.getProgress());
                progressCircle.initToPause();
                break;
            case DownloadStatus.STATUS_FAILED:
//                horPb.setProgress(0);
                Log.i("se7en", this.getClass().getName()
                        + "DownloadStatus.STATU_FAILED" + info.getChapterName());
                progressCircle.initToFAILED();
                break;
            case DownloadStatus.STATUS_UPZIPING:
                CWLog.e("TAT", "C1 ====== DownloadStatus.STATUS_UPZIPING");
//                horPb.setProgress(100);
                progressCircle.initToLoading();
                break;
        }
*/

    }

    private class Hoder {
        public ImageView imageView_download;
    }

    public void setmDownLoadInfoList(List<DownLoadInfo> mDownLoadInfoList) {
        this.mDownLoadInfoList = mDownLoadInfoList;
    }
}
